package com.yaolaizaixian.merchant.order;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yaolaizaixian.merchant.HomeActivity;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.utils.AppManager;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.MyUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.yaolaizaixian.merchant.view.SelectPicPopupWindow;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 补录商户信息
 */
public class MakeUpInfoActivity extends BaseActivity {


    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.tv_makeup_car)
    TextView tvMakeupCar;
    @BindView(R.id.tv_ordermakeup_car)
    EditText tvOrdermakeupCar;
    @BindView(R.id.tv_order_shouqi)
    TextView tvOrderShouqi;
    @BindView(R.id.iv_makeup_select)
    ImageView ivMakeupSelect;
    @BindView(R.id.ll_ordermakeup_selsect)
    AutoLinearLayout llOrdermakeupSelsect;
    @BindView(R.id.et_makeup_remarkes)
    EditText etMakeupRemarkes;
    @BindView(R.id.iv_makeupinfo_image1)
    ImageView ivMakeupinfoImage1;
    @BindView(R.id.iv_makeupinfo_image2)
    ImageView ivMakeupinfoImage2;
    @BindView(R.id.ll_makeup_show)
    AutoLinearLayout llMakeupShow;
    @BindView(R.id.btn_makeup_success)
    Button btnMakeupSuccess;
    @BindView(R.id.rl_all)
    AutoRelativeLayout rlAll;
    private SelectPicPopupWindow menuWindow;

    private static final String TAG = "MakeUpInfoActivity";

    //标记显示隐藏
    private boolean isflag = false;
    //url
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;

    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";

    private File tempFile;
    private Bitmap bitmap;
    //判断点击的是支付凭证1图片 还是支付凭证2图片
    private String postflage = "1";
    private String select = "3";
    private String image1 = "";
    private String image2 = "";

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:
                    String result = (String) msg.obj;
                    LogUtil.LogShitou(TAG, result);
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {
//                        final OrderListModel orderListModel = GsonUtil.jsonToBean(result, OrderListModel.class);

                        //保存成功
                        if (!TextUtils.isEmpty(sign) && "1".equals(sign)) {

                            setResult(101);
                            finish();
                            SharedPreferencesUtil.saveBoolean(MakeUpInfoActivity.this, "makeup", true);
                        } else {
                            startActivity(new Intent(MakeUpInfoActivity.this, HomeActivity.class));
                            finish();
                            AppManager.getAppManager().finishAllActivity();
                        }

                        btnMakeupSuccess.setClickable(true);
                        Toast.makeText(MakeUpInfoActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);


                    } else {

                        btnMakeupSuccess.setClickable(true);

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {

                            showConflictDialog(MakeUpInfoActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(MakeUpInfoActivity.this, "您的账号在其它设备登录");

                        } else {

                            Toast.makeText(MakeUpInfoActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }


                    }
                    break;


            }
        }
    };
    private String orderlifeid;
    private String ordersysno;
    private String userid;
    private String sign;

    @Override
    public void initView() {
        setContentView(R.layout.activity_order_makeupinfo);
    }

    @Override
    public void initData() {

        tvTitleText.setText("补录商品信息");
        //用户id
        userid = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");
        Intent intent = getIntent();
        //耀莱订单号
        orderlifeid = intent.getStringExtra("orderlifeid");
        //订单id
        ordersysno = intent.getStringExtra("ordersysno");

        tvMakeupCar.setText("耀莱订单编号：" + orderlifeid);
        //标记从订单进入
        sign = intent.getStringExtra("sign");

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_back, R.id.iv_makeupinfo_image1, R.id.iv_makeupinfo_image2, R.id.ll_ordermakeup_selsect, R.id.btn_makeup_success})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_back:

                finish();

                break;
            case R.id.ll_ordermakeup_selsect:

                if (!isflag) {

                    llMakeupShow.setVisibility(View.VISIBLE);
                    ivMakeupSelect.setImageResource(R.mipmap.jiantou_shang);
                    tvOrderShouqi.setText("收起");
                    isflag = true;

                } else {

                    llMakeupShow.setVisibility(View.GONE);
                    ivMakeupSelect.setImageResource(R.mipmap.jiantou_xia);
                    tvOrderShouqi.setText("选填项");
                    isflag = false;
                }


                break;

            case R.id.iv_makeupinfo_image1:


                postflage = "1";
                menuWindow = new SelectPicPopupWindow(getApplicationContext(), itemsOnClick);

                menuWindow.showAtLocation((rlAll),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                break;

            case R.id.iv_makeupinfo_image2:

                postflage = "2";
                menuWindow = new SelectPicPopupWindow(getApplicationContext(), itemsOnClick);

                menuWindow.showAtLocation((rlAll),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                break;


            //点击完成
            case R.id.btn_makeup_success:

                checkmakeup();

                break;

        }
    }


    //检查订单补录
    private void checkmakeup() {

        if (TextUtils.isEmpty(tvOrdermakeupCar.getText().toString().trim())) {
            Toasty.error(getApplicationContext(), "请输入商户订单号", Toast.LENGTH_SHORT).show();

            return;
        } else {

            btnMakeupSuccess.setClickable(false);

            String remarks = etMakeupRemarkes.getText().toString().trim();

            if (TextUtils.isEmpty(image1)) {
                image1 = "";
            }
            if (TextUtils.isEmpty(image2)) {
                image2 = "";
            }
            if (TextUtils.isEmpty(remarks)) {
                remarks = "";
            }
            getData(tvOrdermakeupCar.getText().toString().trim(), image1, image2, remarks);

        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // 隐藏弹出窗口
            menuWindow.dismiss();

            switch (v.getId()) {
                case R.id.takePhotoBtn:// 拍照

                    //跳转到调用系统相机
                    Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    intent1.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment
                                    .getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                    //  intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(intent1, REQUEST_CAPTURE);


                    break;
                case R.id.pickPhotoBtn:// 相册选择图片

                    //跳转到调用系统图库
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            "image/*");
                    startActivityForResult(intent, REQUEST_PICK);

                    break;

                case R.id.cancelBtn:// 取消


                    break;

                default:

                    break;
            }
        }
    };

    //返回的结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_PICK) {
            if (data != null) {
                // 得到图片的全路径
                if (resultCode == RESULT_OK) {

                    Uri uri = data.getData();
                    gotoClipActivity(uri);
                }
            }

        } else if (requestCode == REQUEST_CAPTURE) {

            if (MyUtils.hasSdcard()) {

                if (resultCode == RESULT_OK) {

                    tempFile = new File(Environment.getExternalStorageDirectory(),
                            PHOTO_FILE_NAME);
                    gotoClipActivity(Uri.fromFile(tempFile));
                }

            } else {

                Toast.makeText(getApplicationContext(), "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == REQUEST_CROP_PHOTO) {

            if (resultCode == RESULT_OK) {

                final Uri uri = data.getData();
                if (uri == null) {

                    return;
                }

                String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                bitmap = BitmapFactory.decodeFile(cropImagePath);

                if (postflage.equals("1")) {

                    //设置上了，说明bitmap获取到了
                    ivMakeupinfoImage1.setImageBitmap(bitmap);
                    ivMakeupinfoImage1.setScaleType(ImageView.ScaleType.FIT_XY);
                    select = "4";
                    show();

                } else if (postflage.equals("2")) {

                    //设置上了，说明bitmap获取到了
                    ivMakeupinfoImage2.setImageBitmap(bitmap);
                    ivMakeupinfoImage2.setScaleType(ImageView.ScaleType.FIT_XY);
                    select = "5";
                    show();
                }

            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 打开截图界面
     *
     * @param uri
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }


    public static String bitmapToBase64(Bitmap bitmap) {

        String result = "";
        ByteArrayOutputStream bos = null;

        try {
            if (null != bitmap) {
                bos = new ByteArrayOutputStream();

                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);//将bitmap放入字节数组流中

                bos.flush();//将bos流缓存在内存中的数据全部输出，清空缓存
                bos.close();

                byte[] bitmapByte = bos.toByteArray();

                result = Base64.encodeToString(bitmapByte, Base64.DEFAULT);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (null != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    private void show() {
        if (select.equals("4")) {

            image1 = bitmapToBase64(bitmap);

        } else if (select.equals("5")) {

            image2 = bitmapToBase64(bitmap);

        }
    }

    /**
     * 获取订单数据
     * userId	是	string	用户ID
     * masterSysno	是	string	订单ID
     * streamAccount	是	string	流水单号
     * certificate1	是	string	凭证1
     * certificate2	是	string	凭证2
     * unit1	是	string	凭证1类型(如img或者jpeg)
     * unit2	是	string	凭证2类型(如img或者jpeg)
     * remark	是	string	备注
     */
    private void getData(String streamAccount, String certificate1, String certificate2, String remark) {

        try {

            final String url = BaseInfo.URL + "lifeOrder/insertLifedditionalRecording.do";
            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            sortedParams.put("userId", userid);
            sortedParams.put("masterSysno", ordersysno);
            sortedParams.put("streamAccount", streamAccount);

            if (!TextUtils.isEmpty(certificate1))
            {
                sortedParams.put("certificate1", certificate1);
            }
            if (!TextUtils.isEmpty(certificate2))
            {
                sortedParams.put("certificate2", certificate2);
            }

            sortedParams.put("unit1", "png");
            sortedParams.put("unit2", "png");
            sortedParams.put("remark", remark);
            Log.e(TAG, "userId===" + userid);
            Log.e(TAG, "masterSysno===" + ordersysno);
            Log.e(TAG, "streamAccount===" + streamAccount);
            Log.e(TAG, "certificate1====" + certificate1);
            Log.e(TAG, "certificate2====" + certificate2);
            Log.e(TAG, "remark======" + remark);

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            btnMakeupSuccess.setClickable(true);
            Log.e(TAG, e.toString());

        }

        @Override
        public void onResponse(String response, int id) {
            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }

    }

    /**
     * 创建调用系统照相机待存储的临时文件
     *
     * @param savedInstanceState
     */
    private void createCameraTempFile(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.containsKey("tempFile")) {
            tempFile = (File) savedInstanceState.getSerializable("tempFile");
        } else {
            tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"),
                    System.currentTimeMillis() + ".jpg");
        }
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    /**
     * Try to return the absolute file path from the given Uri  兼容了file:///开头的 和 content://开头的情况
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
